'''
交易路由
'''
import sys
import traceback
from app.common.exceptions import GenericException
from app.common.enums import ErrTypes
from sqlalchemy.orm import Session
from app.models import PayProduct, MerchantFee
from app import services

import logging
logger = logging.getLogger(__name__)

def _get_merc_fees_by_pay_type(db: Session, merc_no: str, pay_type: int):
    try:
        results = db.query(MerchantFee).join(PayProduct, PayProduct.product_code == MerchantFee.product_code). \
            filter(
                MerchantFee.merc_no == merc_no,
                PayProduct.pay_type == pay_type,
                ).all()
        '''
        with_entities(MerchantFee.product_code, MerchantFee.product_name, 
                        MerchantFee.pay_channel_code, PayProduct.pay_type).all()
                    '''
        return results
    except Exception as err:
        logger.error(traceback.print_exc)
        raise GenericException(ErrTypes.db_query_error)

def get_merc_fee_info(db: Session, merc_no, pay_type):
    logger.info(">> 交易路由，获取支付产品")
    try:
        merc_fees = _get_merc_fees_by_pay_type(db, merc_no, pay_type)
        if len(merc_fees) > 0:
            merc_fee = merc_fees[0]
            return merc_fee
        else:
            raise GenericException(ErrTypes.fee_no_related_pay_fee)
    except Exception as err:
        logger.error('获取支付产品失败')
        exc_type, exc_value, exc_obj = sys.exc_info()
        traceback.print_exception(exc_type,exc_value,exc_obj,limit=3,file=sys.stdout)
        raise GenericException(ErrTypes.route_get_product_fail)
    

